package com.lframework.xingyun.basedata.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.lframework.starter.common.utils.CollectionUtil;
import com.lframework.starter.web.core.components.resp.PageResult;
import com.lframework.starter.web.core.utils.PageResultUtil;
import com.lframework.starter.web.core.annotations.security.HasPermission;
import com.lframework.starter.web.core.controller.DefaultBaseController;
import com.lframework.starter.web.core.components.resp.InvokeResult;
import com.lframework.starter.web.core.components.resp.InvokeResultBuilder;
import com.lframework.starter.web.core.utils.ExcelUtil;
import com.lframework.xingyun.basedata.bo.product.info.GetProductBo;
import com.lframework.xingyun.basedata.bo.product.info.QueryProductBo;
import com.lframework.xingyun.basedata.bo.product.costcard.GetProductCostCardBo;
import com.lframework.xingyun.basedata.bo.unit.GetUnitBo;
import com.lframework.xingyun.basedata.entity.Product;
import com.lframework.xingyun.basedata.entity.ProductCostCard;
import com.lframework.xingyun.basedata.entity.Unit;
import com.lframework.xingyun.basedata.excel.product.ProductImportListener;
import com.lframework.xingyun.basedata.excel.product.ProductImportModel;
import com.lframework.xingyun.basedata.service.product.*;
import com.lframework.xingyun.basedata.vo.product.info.CreateProductVo;
import com.lframework.xingyun.basedata.vo.product.info.QueryProductVo;
import com.lframework.xingyun.basedata.vo.product.info.UpdateProductVo;
import com.lframework.xingyun.basedata.vo.product.costcard.CreateProductCostCardVo;
import com.lframework.xingyun.basedata.vo.product.costcard.UpdateProductCostCardVo;
import com.lframework.xingyun.basedata.vo.product.shop.SyncProductShopVo;
import com.lframework.xingyun.basedata.vo.product.unit.CalcCostVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 商品管理
 *
 * @author zmj
 */
@Api(tags = "商品管理")
@Validated
@RestController
@RequestMapping("/basedata/product")
public class ProductController extends DefaultBaseController {

  @Autowired
  private ProductService productService;

  @Autowired
  private ProductBundleService productBundleService;

  @Autowired
  private ProductPropertyRelationService productPropertyRelationService;

  @Autowired
  private ProductCostCardService productCostCardService;

  @Autowired
  private ProductShopService productShopService;

  /**
   * 商品列表
   */
  @ApiOperation("商品列表")
  @HasPermission({
          "base-data:product:info:query",
          "base-data:product:info:materials:query",
          "base-data:product:info:sales:query",
          "base-data:product:info:retail:query"
  })
  @GetMapping("/query")
  public InvokeResult<PageResult<QueryProductBo>> query(@Valid QueryProductVo vo) {

    PageResult<Product> pageResult = productService.query(getPageIndex(vo), getPageSize(vo), vo);

    List<Product> datas = pageResult.getDatas();
    List<QueryProductBo> results = null;

    if (!CollectionUtil.isEmpty(datas)) {

      results = datas.stream().map(QueryProductBo::new).collect(Collectors.toList());
    }

    return InvokeResultBuilder.success(PageResultUtil.rebuild(pageResult, results));
  }

  /**
   * 商品详情
   */
  @ApiOperation("商品详情")
  @ApiImplicitParam(value = "ID", name = "id", paramType = "query", required = true)
  @HasPermission({
          "base-data:product:info:query",
          "base-data:product:info:materials:query",
          "base-data:product:info:sales:query",
          "base-data:product:info:retail:query"
  })
  @GetMapping
  public InvokeResult<GetProductBo> get(@NotBlank(message = "ID不能为空！") String id) {

    Product data = productService.findById(id);

    GetProductBo result = new GetProductBo(data);

    return InvokeResultBuilder.success(result);
  }

  /**
   * 新增商品
   */
  @ApiOperation("新增商品")
  @HasPermission({
          "base-data:product:info:add",
          "base-data:product:info:materials:add",
          "base-data:product:info:sales:add",
          "base-data:product:info:retail:add"
  })
  @PostMapping
  public InvokeResult<Void> create(@Valid @RequestBody CreateProductVo vo) {

    productService.create(vo);

    return InvokeResultBuilder.success();
  }

  /**
   * 修改商品
   */
  @ApiOperation("修改商品")
  @HasPermission({
          "base-data:product:info:modify",
          "base-data:product:info:materials:modify",
          "base-data:product:info:sales:modify",
          "base-data:product:info:retail:modify"
  })
  @PutMapping
  public InvokeResult<Void> update(@Valid @RequestBody UpdateProductVo vo) {

    productService.update(vo);

    productService.cleanCacheByKey(vo.getId());

    productPropertyRelationService.cleanCacheByKey(vo.getId());

    productBundleService.cleanCacheByKey(vo.getId());

    return InvokeResultBuilder.success();
  }

  @ApiOperation("下载导入模板")
  @HasPermission({
          "base-data:product:info:import",
          "base-data:product:info:materials:import",
          "base-data:product:info:sales:import",
          "base-data:product:info:retail:import"
  })
  @GetMapping("/import/template")
  public void downloadImportTemplate() {
    ExcelUtil.exportXls("商品导入模板", ProductImportModel.class);
  }

  @ApiOperation("导入")
  @HasPermission({
          "base-data:product:info:import",
          "base-data:product:info:materials:import",
          "base-data:product:info:sales:import",
          "base-data:product:info:retail:import"
  })
  @PostMapping("/import")
  public InvokeResult<Void> importExcel(@NotBlank(message = "ID不能为空") String id,
      @NotNull(message = "请上传文件") MultipartFile file) {

    ProductImportListener listener = new ProductImportListener();
    listener.setTaskId(id);
    ExcelUtil.read(file, ProductImportModel.class, listener).sheet().doRead();

    return InvokeResultBuilder.success();
  }

  /**
   * 根据商品ID查询商品单位
   * @param productId
   * @return
   */
  @ApiOperation("根据商品ID查询商品单位")
  @GetMapping("/unit")
  public InvokeResult<List<GetUnitBo>> getUnitByProductId(@RequestParam(required = false) String productId) {
      List<Unit> unitByProductId = productService.getUnitByProductId(productId);

      List<GetUnitBo> result = unitByProductId.stream()
              .map(GetUnitBo::new)
              .collect(Collectors.toList());

      return InvokeResultBuilder.success(result);
  }

  /**
   * 计算用量成本
   * @param vo
   * @return
   */
  @ApiOperation("计算用量成本")
  @GetMapping("/unit/calc")
  public InvokeResult<BigDecimal> calcCost(@Valid CalcCostVo vo) {
      BigDecimal unitCostPrice = productService.calcCost(vo.getProductId(), vo.getUnitId(), vo.getNum());
      return InvokeResultBuilder.success(unitCostPrice);
  }

  // ==================== 成本卡相关接口 ====================

  /**
   * 获取商品成本卡
   */
  @ApiOperation("获取商品成本卡")
  @ApiImplicitParam(value = "商品ID", name = "productId", paramType = "query", required = true)
  @HasPermission({
          "base-data:product:costcard:import",
  })
  @GetMapping("/costcard")
  public InvokeResult<GetProductCostCardBo> getCostCard(@NotBlank(message = "商品ID不能为空！") String productId) {

    ProductCostCard costCard = productCostCardService.getByProductId(productId);
    
    if (costCard == null) {
      return InvokeResultBuilder.success(null);
    }

    GetProductCostCardBo result = new GetProductCostCardBo(costCard);

    return InvokeResultBuilder.success(result);
  }

  /**
   * 创建商品成本卡
   */
  @ApiOperation("创建商品成本卡")
  @HasPermission({"base-data:product:costcard:add"})
  @PostMapping("/costcard")
  public InvokeResult<Void> createCostCard(@Valid @RequestBody CreateProductCostCardVo vo) {

    productCostCardService.create(vo);

    return InvokeResultBuilder.success();
  }

  /**
   * 更新商品成本卡
   */
  @ApiOperation("更新商品成本卡")
  @HasPermission({"base-data:product:costcard:modify"})
  @PutMapping("/costcard")
  public InvokeResult<Void> updateCostCard(@Valid @RequestBody UpdateProductCostCardVo vo) {

    productCostCardService.update(vo);

    return InvokeResultBuilder.success();
  }

  /**
   * 删除商品成本卡
   */
  @ApiOperation("删除商品成本卡")
  @ApiImplicitParam(value = "ID", name = "id", paramType = "query", required = true)
  @HasPermission({"base-data:product:costcard:delete"})
  @DeleteMapping("/costcard")
  public InvokeResult<Void> deleteCostCard(@NotBlank(message = "ID不能为空！") String id) {

    productCostCardService.delete(id);

    return InvokeResultBuilder.success();
  }

  /**
   * 根据商品ID删除成本卡
   */
  @ApiOperation("根据商品ID删除成本卡")
  @ApiImplicitParam(value = "商品ID", name = "productId", paramType = "query", required = true)
  @HasPermission({"base-data:product:costcard:delete"})
  @DeleteMapping("/costcard/by-product")
  public InvokeResult<Void> deleteCostCardByProduct(@NotBlank(message = "商品ID不能为空！") String productId) {

    productCostCardService.deleteByProductId(productId);

    return InvokeResultBuilder.success();
  }

  @ApiOperation("商品信息同步至门店")
  @HasPermission({
          "base-data:product:info:retail:sync",
          "base-data:product:info:sales:sync",
          "base-data:product:info:materials:sync",
  })
  @PostMapping("/sync/shop")
  public InvokeResult<Void> syncProductShop(@RequestBody @Valid SyncProductShopVo vo) {
      StrUtil.split(vo.getShopId(), ",").forEach(shopId -> {
          SyncProductShopVo normalShop = BeanUtil.copyProperties(vo, SyncProductShopVo.class);
          normalShop.setShopId(shopId);
          productShopService.syncProductShop(normalShop);
      });
      return InvokeResultBuilder.success();
  }
}
